import { message } from 'ant-design-vue';
import qs from 'querystringify';
import dayjs from 'dayjs';
import { IGoodsRelation } from '@/type';
/**
 *
 * @param all 解析树
 * @returns
 */
export const parseTree = (all: any[]) => {
  var MENU_DATA: any = [];
  all.forEach(function (it) {
    if (
      !MENU_DATA.find(function (ele) {
        return ele.id == it.id;
      })
    ) {
      MENU_DATA.push(it);
    }
  });

  MENU_DATA.forEach(function (it) {
    MENU_DATA.forEach(function (ele) {
      if (it.id == ele.pId) {
        if (it.children) {
          if (!it.children.find((child) => child.id == ele.id)) it.children.push(ele);
        } else {
          it.children = new Array();
          it.children.push(ele);
        }
      }
    });
  });
  var resourceTree = MENU_DATA.filter(function (it) {
    return it.pId == '' || it.pId == '0';
  });
  return resourceTree;
};

/**
 * 获取url参数
 * @param name
 */
export const getUrlParameter = (name: string) => {
  const index = window.location.href.indexOf('?');
  const url = window.location.href.substr(index);
  let up: any = {};
  if (url.indexOf('?') != -1) {
    var str = url.substr(1);
    var str2 = str.split('&');
    for (let i = 0; i < str2.length; i++) {
      up[str2[i].split('=')[0]] = decodeURI(str2[i].split('=')[1]);
    }
  }
  return up[name];
};

export const getUrlSearchParams = (key: string): string => {
  const search = window.location.search || window.location.href.split('?')[1];
  if (!search) {
    return '';
  }
  // console.log("search", search);
  const params = qs.parse(search);
  return params[key];
};

/**
 * 获取url参数
 * @param name
 */
export const getAllUrlParameter = () => {
  const index = window.location.href.indexOf('?');
  const url = window.location.href.substr(index);
  let up: any = {};
  if (url.indexOf('?') != -1) {
    var str = url.substr(1);
    var str2 = str.split('&');
    for (let i = 0; i < str2.length; i++) {
      up[str2[i].split('=')[0]] = decodeURI(str2[i].split('=')[1]);
    }
  }
  return up;
};

/**
 *
 * @param date 时间
 * @param fmt 格式
 */
export const formatStr = (date: number | Date, fmt: string) => {
  if (!date) {
    return '';
  }
  if (!String.prototype.padStart) {
    String.prototype.padStart = function padStart(targetLength, padString) {
      targetLength = targetLength >> 0; //floor if number or convert non-number to 0;
      padString = String(typeof padString !== 'undefined' ? padString : ' ');
      if (this.length > targetLength) {
        return String(this);
      } else {
        targetLength = targetLength - this.length;
        if (targetLength > padString.length) {
          padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
        }
        return padString.slice(0, targetLength) + String(this);
      }
    };
  }
  const time: Date = new Date(date);
  let ret;
  const opt: any = {
    'Y+': time.getFullYear().toString(), // 年
    'm+': (time.getMonth() + 1).toString(), // 月
    'd+': time.getDate().toString(), // 日
    'H+': time.getHours().toString(), // 时
    'M+': time.getMinutes().toString(), // 分
    'S+': time.getSeconds().toString(), // 秒
  };
  for (let k in opt) {
    ret = new RegExp('(' + k + ')').exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'));
    }
  }
  return fmt;
};

/**
 * @description 倒计时解析
 * @param {String} 参数名 参数描述
 * @reference
 */
export const remainTime = function (lefttime: number): {
  d: number;
  h: number;
  m: number;
  s: number;
} {
  if (lefttime <= 0) return { d: 0, h: 0, m: 0, s: 0 };
  const leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)); //计算天数
  const lefth = Math.floor((lefttime / (1000 * 60 * 60)) % 24); //计算小时数
  const leftm = Math.floor((lefttime / (1000 * 60)) % 60); //计算分钟数
  const lefts = Math.floor((lefttime / 1000) % 60); //计算秒数
  return {
    d: leftd,
    h: lefth,
    m: leftm,
    s: lefts,
  }; //返回倒计时的字符串
};

/**范围日期内生成日期序列 */
export const dateRangeSequence = (start:any, end:any) => {
  const sequences: { label: string; value?: string }[] = [];
  start = dayjs(start).format('YYYY-MM-DD');
  while (new Date(start).getTime() <= new Date(end).getTime()) {
    sequences.push({ label: start });
    start = dayjs(new Date(start).getTime() + 1000 * 60 * 60 * 24).format('YYYY-MM-DD');
  }
  return sequences;
};

/**
 * 获取上月日期
 */
export const getLastMonth = () => {
  const nowDate = new Date();
  let year = nowDate.getFullYear();
  let month: any = nowDate.getMonth();
  if (month == 0) {
    month = 12;
    year = year - 1;
  }
  if (month < 10) {
    month = '0' + month;
  }
  return year + '-' + month;
};

interface IOptionsType {
  labelName: string;
  valueName: string;
}
/**
 * 根据值获取状态
 * @param data
 * @param type
 * @param options
 */
export const getStateValue = (data: any, type: any, options: IOptionsType = { labelName: 'label', valueName: 'value' }) => {
  if (!type || type == '') {
    return '';
  }
  let text = '';
  data.forEach(function (item: any) {
    if (item[options.valueName] == type) {
      text = item[options.labelName];
    }
  });
  return text;
};

/**
 * 获取几天前几天后日期
 * @param day
 * @param date
 */
export const getNextDate = (day: number, date?: any) => {
  var dd = date ? new Date(date) : new Date();
  dd.setDate(dd.getDate() + day);
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1;
  var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate();
  return y + '-' + m + '-' + d;
};

/**
 * 获取身份证的年龄与性别
 * @param IDCord
 */
export const analyzeIDCard = (IDCord: string) => {
  let sexAndAge: any = {};
  //获取用户身份证号码
  let userCard = IDCord;
  //如果用户身份证号码为undefined则返回空
  if (!userCard) {
    return sexAndAge;
  }

  // 获取性别

  let len = userCard.length;
  let strBirthday = '';
  if (len == 18) {
    if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
      sexAndAge.sex = '男'; //0
    } else {
      sexAndAge.sex = '女'; //1
    }
    //处理18位的身份证号码从号码中得到生日和性别代码
    strBirthday = userCard.substr(6, 4) + '/' + userCard.substr(10, 2) + '/' + userCard.substr(12, 2);
  }
  if (len == 15) {
    if (parseInt(userCard.substr(14, 1)) % 2 == 1) {
      sexAndAge.sex = '男'; //0
    } else {
      sexAndAge.sex = '女'; //1
    }
    let birthdayValue = '';
    birthdayValue = userCard.charAt(6) + userCard.charAt(7);
    if (parseInt(birthdayValue) < 10) {
      strBirthday = '20' + userCard.substr(6, 2) + '/' + userCard.substr(8, 2) + '/' + userCard.substr(10, 2);
    } else {
      strBirthday = '19' + userCard.substr(6, 2) + '/' + userCard.substr(8, 2) + '/' + userCard.substr(10, 2);
    }
  }
  //时间字符串里，必须是“/”
  let birthDate = new Date(strBirthday);
  let nowDateTime = new Date();
  let age = nowDateTime.getFullYear() - birthDate.getFullYear();
  //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
  if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
    age--;
  }
  // 得到年龄
  sexAndAge.age = age;
  // 返回 性别和年龄
  return sexAndAge;
};

export function notEmptyArray(arr?: any) {
  return arr instanceof Array && arr.length > 0;
}

/**
 *
 * @param form 获取表单值
 * @param callback
 * @param alert
 * @returns
 */
export const getFormValue = async (form:any, callback:any, alert = true) => {
  try {
    const fields = await form.validateFields();
    callback(fields);
  } catch (e: any) {
    const { errorFields } = e;
    if (!notEmptyArray(errorFields)) {
      callback(form.getFieldsValue());
      return;
    }
    if (alert) message.error(errorFields[0].errors[0]);
    form.getFieldInstance(errorFields[0].name[0]).focus();
    return;
  }
};

/**
 * 在区间内生成随机数
 * @param start
 * @param end
 * @returns
 */
export function stochastic(start:any, end:any) {
  return Math.random() * (end - start) + start;
}

/**
 * 剔除空属性
 */
export const pickNotNull = (obj: any) => {
  const newObj:any = { ...obj };
  //@ts-ignore
  for (let k: string in newObj) {
    if (newObj[k] == null) {
      delete newObj[k];
    }
  }

  return newObj;
};

//下载静态文件
export const downloadUrl = (path: string) => {
  return import.meta.env.BASE_URL + path;
};

export const isValueEmpty = (value:any) => {
  return value === '' || value === undefined || value === null;
};

/**
 * @description 返回hex唯一key
 * @param {String} 参数名 参数描述
 * @reference
 */
export function uuid(): string {
  var s: any = [];
  var hexDigits = '0123456789abcdef';
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = '-';

  var uuid = s.join('');
  return uuid;
}

// 把商品的数据字段转成数据库定义的字段
import { CommonStore } from '@/store';
export function parseGoods(obj:any) {
  const commonStore = CommonStore();
  const name = commonStore.$state.user?.userName;
  return {
    goodsCode: obj.goods_code,
    goodsName: obj.goods_name,
    categoryLevel2: obj.prod_cate_lev2_name,
    categoryCode: obj.prod_cate_lev2_code,
    categoryLevel4: obj.prod_cate_lev4_name,
    categoryLevel4code: obj.prod_cate_lev4_code,
    purClass: obj.purc_clas_lev3_name,
    saleQtyHq: obj.sale_qty_hq,
    creatorName: name,
    mfrPolicy: '',
  };
}

/**
 * @description 筛选商品品类
 * @export
 */
export function filterCategary(arr:any, str:any) {
  let names:any = [];
  arr.forEach((item:any) => {
    str.split(',')?.map((id:any) => {
      // console.log(id,item.id)
      if (id == item.id) {
        console.log(item);
        names.push(item.name);
      }
    });
  });
  return names.length ? names.join(', ') : '';
}

/**
 * @description 获取数组中重复的元素
 * @author yangwen
 * @param {string[]} arr
 * @return {*}
 */
export const getRepeatList = (arr: string[]) => {
  const repeatList: string[] = [];
  let hash:any = {};
  arr.forEach((item:any) => {
    if (!hash[item]) {
      hash[item] = item;
    } else if (hash[item] && !repeatList.includes(item)) {
      repeatList.push(item);
    }
  });

  return repeatList;
};

export const formatDate = (date:any, format = 'YYYY-MM-DD') => {
  if (date) {
    return dayjs(date).format(format);
  }
  return;
};

/**
 * @description 数组根据某个值进行分割为多个数组
 * @author yangwen
 * @param {any[]} array
 * @param {number} groupNum
 * @return {*}  {any[][]}
 */
export const getGroupedList = (array: any[], groupNum: number): any[][] => {
  if (array.length === 0 || groupNum === 0) {
    return array;
  }

  let index = 0;
  const newArray: any[] = [];

  while (index < array.length) {
    newArray.push(array.slice(index, (index += groupNum)));
  }
  return newArray;
};

/**
 * @description 常规数组去重
 * @author yangwen
 * @param {string[]} arr
 * @return {*}  {string[]}
 */
export const dedup = (arr: string[]): string[] => Array.from(new Set(arr));

export const giftSum = (list:any) => {
  return list.reduce((pre:any, cur:any) => {
    return pre + (parseFloat(cur.quantity) || 1);
  }, 0);
};

/**
 * @description 格式化指定品类选中数据展示
 * @author yangwen
 * @param {IGoodsRelation[]} addedCategoryList
 * @return {*}
 */
export const formatCategoryInputText = (addedCategoryList: IGoodsRelation[]) => {
  let inputText: string = '';
  if (addedCategoryList.length <= 2) {
    addedCategoryList.forEach((addedItem, addedIndex) => {
      inputText += `${addedIndex > 0 ? '; ' : ''}${addedItem.categoryLv4Name}`;
    });
  } else {
    inputText += addedCategoryList[0].categoryLv4Name || '';
    inputText += `, 及其他${addedCategoryList.length - 1}条品类`;
  }
  return inputText;
};
